// handlers/StaticFileHandler.js
const BaseHandler = require('./BaseHandler');
const fs = require('fs');
const path = require('path');

class StaticFileHandler extends BaseHandler {
    async handle(req, res, filePath) {
        try {
            if (!await this.fileExists(filePath)) {
                return this.sendError(res, 404, 'File not found');
            }

            const stats = await fs.promises.stat(filePath);
            const ext = path.extname(filePath).toLowerCase();
            const contentType = this.getMimeType(filePath);

            // 设置响应头
            res.setHeader('Content-Type', contentType);
            res.setHeader('Content-Length', stats.size);
            res.setHeader('Cache-Control', 'public, max-age=3600'); // 缓存1小时

            // 对于文本文件，设置字符集
            if (contentType.startsWith('text/')) {
                res.setHeader('Content-Type', contentType + '; charset=utf-8');
            }

            // 使用流式传输
            const stream = fs.createReadStream(filePath);

            stream.on('error', (error) => {
                console.error('Error reading file:', error);
                if (!res.headersSent) {
                    this.sendError(res, 500, 'Error reading file');
                }
            });

            stream.pipe(res);

        } catch (error) {
            console.error('Error processing static file:', error);
            this.sendError(res, 500, 'Failed to process file');
        }
    }
}

module.exports = StaticFileHandler;